/*
 * Copyright Hundsun Technologies Inc. All Rights Reserved.
 */

package util

import (
	"fmt"

	"github.com/golang/protobuf/proto"
	"hundsun.com/hsl/hschain/common/types"
	"hundsun.com/hsl/hschain/protos"
	pbcom "hundsun.com/hsl/hschain/protos/common"
	"hundsun.com/hsl/hschain/protos/ledger"
	"hundsun.com/hsl/hschain/store/db"
)

const (
	// NamespaceBalanceFreezeUnfreezeRecord 未解冻记录命名空间
	NamespaceBalanceFreezeUnfreezeRecord = "ns.bfuf."
)

// 该freeze_record_example.go文件目前只做示例，后续具体负责人进行开发

// FreezeRecord 冻结记录
type FreezeRecord struct {
	get db.DatabaseGet
}

// NewFreezeRecord 新建冻结记录
func NewFreezeRecord(get db.DatabaseGet) *FreezeRecord {
	return &FreezeRecord{get: get}
}

// GetFreezeRecord 获取冻结记录
func (fr *FreezeRecord) GetFreezeRecord(location *pbcom.TxLocation) (*ledger.BalanceFreezeUnfreezeRecord, error) {
	if fr.get == nil {
		return nil, types.ErrNotFound
	}
	v, err := fr.get.Get(db.GenDBKey([]byte(NamespaceBalanceFreezeUnfreezeRecord),
		genFreezeRecordcKey(location.GetBlockNumber(), location.GetTransactionIndex())))
	if err != nil {
		return nil, err
	}
	rec := &ledger.BalanceFreezeUnfreezeRecord{}
	err = proto.Unmarshal(v, rec)
	if err != nil {
		return nil, err
	}
	return rec, nil
}

// FreezeRecordKV 冻结记录KV
func FreezeRecordKV(rec *ledger.BalanceFreezeUnfreezeRecord) (*pbcom.KeyValue, error) {
	kv := &pbcom.KeyValue{}
	height := rec.FreezeTx.BlockNumber
	index := rec.FreezeTx.TransactionIndex
	kv.Key = db.GenDBKey([]byte(NamespaceBalanceFreezeUnfreezeRecord), genFreezeRecordcKey(height, index))
	v, err := proto.Marshal(rec)
	if err != nil {
		return nil, err
	}
	kv.Value = v
	return kv, nil
}

func genFreezeRecordcKey(height uint64, index int32) []byte {
	return []byte(fmt.Sprintf("%d%s%d", height, protos.EsDocIDSeparator, index))
}
